<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getTravelPlanById, updateTravelPlan } from '../../api/travelPlan'
import { authUtils } from '../../utils/auth'
import { getRoutesByPlanId } from '../../api/route'

const route = useRoute()
const router = useRouter()
const planId = route.params.id

// 编辑模式状态控制
const isEditMode = ref(false)

// 只读模式：?readonly=1 / true
const readonlyMode = computed(() => {
  const q = route.query?.readonly
  return q === '1' || q === 'true'
})

// 切换编辑模式
const toggleEditMode = () => {
  if (readonlyMode.value) {
    ElMessage.warning('当前为仅浏览模式，不能编辑行程')
    return
  }
  isEditMode.value = !isEditMode.value
}

// 旅行计划数据
const travelPlan = ref({
  id: planId,
  title: '日本东京五日游',
  description: '这是一次精彩的东京之旅，将游览东京塔、迪士尼乐园等著名景点',
  cityName: '东京',
  days: 5,
  startDate: '2023-10-01',
  isPublic: true,
  status: 'approved' // pending, approved, rejected
})

// 每日计划列表
const dailyPlans = ref([])

// 新增：按日关联的路线映射与计数
const routesByDay = ref({})
const routeCounts = ref({})

// —— 高德地点联想：与路线规划保持一致的体验 ——
const AMAP_KEY = 'c3ea87d6c59607d6879ebfbe1ac1b973'
const AMAP_SECURITY = 'efdc950db73cf46818881d663511bbc9'
let geocoder = null
const poiSearchRef = ref(null)

const loadAMapLite = () => {
  return new Promise((resolve, reject) => {
    if (window.AMap) {
      if (!geocoder) {
        window.AMap.plugin('AMap.Geocoder', () => {
          geocoder = new window.AMap.Geocoder()
          resolve()
        })
      } else {
        resolve()
      }
      return
    }
    window._AMapSecurityConfig = { securityJsCode: AMAP_SECURITY }
    const script = document.createElement('script')
    script.src = `https://webapi.amap.com/maps?v=2.0&key=${AMAP_KEY}&plugin=AMap.Geocoder,AMap.AutoComplete,AMap.PlaceSearch`
    script.onload = () => {
      window.AMap.plugin('AMap.Geocoder', () => {
        geocoder = new window.AMap.Geocoder()
        resolve()
      })
    }
    script.onerror = () => reject(new Error('AMap脚本加载失败'))
    document.head.appendChild(script)
  })
}

// 根据目标城市获取/更新 PlaceSearch 实例
const ensurePoiSearch = (city) => new Promise((resolve) => {
  window.AMap.plugin('AMap.PlaceSearch', () => {
    const targetCity = city || '全国'
    if (!poiSearchRef.value) {
      poiSearchRef.value = new window.AMap.PlaceSearch({ city: targetCity, citylimit: targetCity !== '全国' })
      poiSearchRef.value.__city = targetCity
    } else {
      if (poiSearchRef.value.__city !== targetCity) {
        if (typeof poiSearchRef.value.setCity === 'function') {
          poiSearchRef.value.setCity(targetCity)
        }
        if (typeof poiSearchRef.value.setCityLimit === 'function') {
          poiSearchRef.value.setCityLimit(targetCity !== '全国')
        }
        poiSearchRef.value.__city = targetCity
      }
    }
    resolve(poiSearchRef.value)
  })
})

// 获取某一天的优先城市：每日计划城市 > 旅行计划城市 > 全国
const getPreferredCityForDay = (dayIndex) => {
  const dp = dailyPlans.value[dayIndex]
  return (dp?.cityName || travelPlan.value.cityName || '全国')
}

// 在指定城市范围内获取自动完成建议
const fetchLocationSuggestions = async (dayIndex, query, cb) => {
  try {
    if (!query) { cb([]); return }
    await loadAMapLite()
    const city = getPreferredCityForDay(dayIndex)
    window.AMap.plugin('AMap.AutoComplete', () => {
      const ac = new window.AMap.AutoComplete({ city: city || '全国', citylimit: (city || '全国') !== '全国' })
      ac.search(query, (status, result) => {
        if (status === 'complete' && result.tips) {
          const list = result.tips
            .filter(t => t.name)
            .map(t => ({ value: t.name, tip: t }))
          cb(list)
        } else {
          cb([])
        }
      })
    })
  } catch (_) {
    cb([])
  }
}

// 解析名称为POI（用于在选择联想项后保证名称标准化）
const resolvePoiForDay = async (name, dayIndex) => {
  await loadAMapLite()
  const ps = await ensurePoiSearch(getPreferredCityForDay(dayIndex))
  return new Promise((resolve) => {
    ps.search(name, (status, result) => {
      if (status === 'complete' && result?.poiList?.pois?.length) {
        const poi = result.poiList.pois[0]
        resolve({ name: poi.name, location: poi.location, cityname: poi.cityname })
      } else {
        if (!geocoder) {
          window.AMap.plugin('AMap.Geocoder', () => {
            geocoder = new window.AMap.Geocoder()
            geocoder.getLocation(name, (s, r) => resolve({ name, location: r?.geocodes?.[0]?.location || null, cityname: getPreferredCityForDay(dayIndex) }))
          })
        } else {
          geocoder.getLocation(name, (s, r) => resolve({ name, location: r?.geocodes?.[0]?.location || null, cityname: getPreferredCityForDay(dayIndex) }))
        }
      }
    })
  })
}

const onLocationSelect = async (dayIndex, locationIndex, item) => {
  const poi = await resolvePoiForDay(item.value, dayIndex)
  // 写回规范化名称；每日计划数据结构不存坐标，这里仅更新名称
  dailyPlans.value[dayIndex].locations[locationIndex].name = poi.name
}

// 新增：读取/统计本地已保存路线
const readRoutesByPlan = () => {
  try {
    const raw = localStorage.getItem('routesByPlan')
    return raw ? JSON.parse(raw) : {}
  } catch (_) {
    return {}
  }
}
const loadRouteCounts = () => {
  const counts = {}
  dailyPlans.value.forEach(dp => {
    counts[dp.id] = routesByDay.value[dp.id] ? 1 : 0
  })
  routeCounts.value = counts
}

// 新增：加载该计划下的已保存路线，并按每日计划ID建立映射
const loadRoutesForPlan = async () => {
  try {
    const res = await getRoutesByPlanId(planId)
    const list = res?.success ? res.data : (Array.isArray(res) ? res : [])
    const map = {}
    list.forEach(r => {
      if (r.dailyPlanId) map[Number(r.dailyPlanId)] = r
    })
    routesByDay.value = map
    loadRouteCounts()
  } catch (e) {
    console.error('获取计划关联路线失败:', e)
  }
}

// 获取旅行计划详情
const fetchTravelPlan = async () => {
  try {
    const data = await getTravelPlanById(planId)
    travelPlan.value = {
      id: data.id,
      title: data.title || '',
      description: data.description || '',
      cityName: data.cityName || '',
      days: data.days || 1,
      startDate: data.startDate || '',
      isPublic: !!data.isPublic,
      status: data.status || 'pending'
    }
    // 如果不是本人计划，自动进入只读模式
    const currentUserId = authUtils.getCurrentUser()?.id
    const isOwner = Number(data.userId) === Number(currentUserId)
    if (!isOwner) {
      // 覆盖到只读视图
      if (!readonlyMode.value) {
        router.replace({ path: `/travel-plan/${planId}`, query: { ...route.query, readonly: '1' } })
        ElMessage.info('该旅行计划属于其他用户，已切换为只读模式')
      }
      isEditMode.value = false
    }
    if (Array.isArray(data.dailyPlans) && data.dailyPlans.length > 0) {
      dailyPlans.value = data.dailyPlans
      await loadRoutesForPlan()
    } else {
      generateDailyPlans()
    }
  } catch (error) {
    console.error('获取旅行计划详情失败:', error)
    ElMessage.error('获取旅行计划详情失败')
  }
}

// 生成每日计划数据（去除示例地点，按天数生成空列表）
const generateDailyPlans = () => {
  const plans = []
  const startDate = travelPlan.value.startDate ? new Date(travelPlan.value.startDate) : new Date()
  for (let i = 0; i < Number(travelPlan.value.days || 1); i++) {
    const currentDate = new Date(startDate)
    currentDate.setDate(startDate.getDate() + i)
    plans.push({
      id: i + 1,
      day: i + 1,
      date: formatDate(currentDate),
      cityName: travelPlan.value.cityName || '',
      locations: [],
      note: i === 0 ? '抵达日，轻松行程' : i === Number(travelPlan.value.days || 1) - 1 ? '返程日，注意时间安排' : '充实的一天'
    })
  }
  dailyPlans.value = plans
  loadRouteCounts()
}

// 格式化日期
const formatDate = (date) => {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

// 添加地点
const addLocation = (dayIndex) => {
  dailyPlans.value[dayIndex].locations.push({
    id: Date.now(),
    name: '',
    type: 'custom', // attraction, custom
    time: '',
    note: ''
  })
}

// 删除地点
const removeLocation = (dayIndex, locationIndex) => {
  dailyPlans.value[dayIndex].locations.splice(locationIndex, 1)
}

// 保存每日计划（调用后端更新接口）
const saveDailyPlans = async () => {
  if (readonlyMode.value) {
    ElMessage.warning('当前为仅浏览模式，不能保存')
    return
  }
  try {
    await updateTravelPlan(planId, { dailyPlans: dailyPlans.value })
    ElMessage.success('每日计划保存成功')
    isEditMode.value = false
    await fetchTravelPlan()
  } catch (error) {
    console.error('保存每日计划失败:', error)
    ElMessage.error('保存每日计划失败')
  }
}

// 返回旅行计划列表页面
const goBack = () => {
  if (readonlyMode.value) {
    router.push({ path: '/community', query: { tab: 'plans' } })
  } else {
    router.push('/travel-plan')
  }
}

// 编辑旅行计划基本信息
const editPlan = () => {
  if (readonlyMode.value) {
    ElMessage.warning('当前为仅浏览模式，不能编辑基本信息')
    return
  }
  router.push(`/travel-plan/${planId}/edit`)
}

// 顶部入口已移除：整计划路线规划

// 新增：针对某一日进行路线规划，自动预填当日前两个地点
const goToRoutePlanning = (dailyPlanId) => {
  if (readonlyMode.value) {
    ElMessage.warning('当前为仅浏览模式，无法规划路线')
    return
  }
  const dp = dailyPlans.value.find(d => d.id === dailyPlanId)
  const points = (dp?.locations || []).map(l => l.name).filter(Boolean)
  router.push({
    path: '/route-planning',
    query: { 
      planId, 
      dailyPlanId, 
      points: encodeURIComponent(JSON.stringify(points)) 
    }
  })
}

// 新增：查看/编辑某日已关联的路线
const viewDayRoute = (dailyPlanId) => {
  const r = routesByDay.value[dailyPlanId]
  if (readonlyMode.value) {
    if (r?.id) {
      router.push({ path: '/route-planning', query: { routeId: r.id, readonly: '1' } })
    } else {
      ElMessage.info('暂无关联路线')
    }
    return
  }
  if (r?.id) {
    router.push(`/route-planning?routeId=${r.id}`)
  } else {
    goToRoutePlanning(dailyPlanId)
  }
}

// 取消编辑
const cancelEdit = () => {
  // 提示用户确认取消编辑
  ElMessageBox.confirm('确定要取消编辑吗？未保存的修改将会丢失', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 重新获取数据，放弃修改
    fetchTravelPlan()
    isEditMode.value = false
  }).catch(() => {
    // 用户取消操作，继续编辑
  })
}

// 删除某天的行程
const removeDailyPlan = (dayIndex) => {
  ElMessageBox.confirm('确定要删除这一天的行程吗？相关的路线规划也会被解除关联', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 删除该天行程
    dailyPlans.value.splice(dayIndex, 1);
    
    // 重新排序天数
    dailyPlans.value.forEach((plan, idx) => {
      plan.day = idx + 1;
    });
    
    // 更新旅行计划的天数
    travelPlan.value.days = dailyPlans.value.length;
    
    ElMessage.success('已删除该天行程');
  }).catch(() => {
    // 用户取消操作
  });
}

// 添加天数
const addDailyPlan = () => {
  if (readonlyMode.value) {
    ElMessage.warning('当前为仅浏览模式，不能添加天数')
    return
  }
  // 获取当前最后一天的日期
  const lastDay = dailyPlans.value[dailyPlans.value.length - 1];
  const lastDate = lastDay ? new Date(lastDay.date) : new Date(travelPlan.value.startDate);
  
  // 新增一天（日期为最后一天+1）
  const newDate = new Date(lastDate);
  newDate.setDate(lastDate.getDate() + 1);
  
  // 创建新的每日计划
  const newDayPlan = {
    id: Date.now(), // 临时ID，保存时后端会分配真实ID
    day: dailyPlans.value.length + 1,
    date: formatDate(newDate),
    cityName: travelPlan.value.cityName || '',
    locations: [],
    note: '新增行程'
  };
  
  // 添加到每日计划列表
  dailyPlans.value.push(newDayPlan);
  
  // 更新旅行计划的天数
  travelPlan.value.days = dailyPlans.value.length;
  
  ElMessage.success('已添加新的行程天数');
}

onMounted(() => {
  fetchTravelPlan()
})
</script>

<template>
  <div class="travel-plan-detail">
    <div class="plan-header">
      <h1 class="plan-title">{{ travelPlan.title }}</h1>
      
      <div class="plan-actions">
        <el-button @click="goBack">返回</el-button>
        <el-button v-if="!readonlyMode" type="primary" @click="editPlan">编辑基本信息</el-button>
      </div>
    </div>
    
    <div class="plan-info">
      <el-descriptions :column="3" border>
        <el-descriptions-item label="主要城市">{{ travelPlan.cityName }}</el-descriptions-item>
        <el-descriptions-item label="出行天数">{{ travelPlan.days }}天</el-descriptions-item>
        <el-descriptions-item label="出行日期">{{ travelPlan.startDate }}</el-descriptions-item>
        <el-descriptions-item label="是否公开">
          <el-tag :type="travelPlan.isPublic ? 'success' : 'info'">
            {{ travelPlan.isPublic ? '公开' : '私密' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="审核状态" v-if="travelPlan.isPublic">
          <el-tag :type="travelPlan.status === 'approved' ? 'success' : travelPlan.status === 'rejected' ? 'danger' : 'warning'">
            {{ travelPlan.status === 'approved' ? '已通过' : travelPlan.status === 'rejected' ? '已拒绝' : '审核中' }}
          </el-tag>
        </el-descriptions-item>
      </el-descriptions>
      
      <div class="plan-description">
        <h3>计划描述</h3>
        <p>{{ travelPlan.description }}</p>
      </div>
    </div>
    
    <div class="daily-plans">
      <div class="daily-plans-header">
        <h2>每日计划规划</h2>
        <div class="edit-actions" v-if="!readonlyMode">
          <el-button v-if="!isEditMode" type="primary" @click="toggleEditMode">编辑行程</el-button>
          <template v-else>
            <el-button type="success" @click="saveDailyPlans">保存</el-button>
            <el-button @click="cancelEdit">取消</el-button>
            <el-button type="primary" @click="addDailyPlan">添加天数</el-button>
          </template>
        </div>
      </div>
      
      <div v-for="(plan, dayIndex) in dailyPlans" :key="dayIndex" class="daily-plan-item">
        <div class="daily-plan-header">
          <h3>第{{ plan.day }}天 ({{ plan.date }})</h3>
          <el-input v-if="isEditMode" v-model="plan.note" placeholder="添加当日备注，如'轻松行程'、'重点拍照'等" class="day-note-input"></el-input>
          <div v-else class="day-note">{{ plan.note }}</div>
          <div class="day-route-actions">
            <el-tag v-if="routesByDay[plan.id]" type="success" class="route-badge">
              关联路线：{{ routesByDay[plan.id].title || '未命名路线' }}
            </el-tag>
            <el-tag v-else type="info" class="route-badge">未关联路线</el-tag>
            <el-button v-if="!readonlyMode" size="small" type="success" @click="viewDayRoute(plan.id)">
              {{ routesByDay[plan.id] ? '查看/编辑路线' : '规划路线' }}
            </el-button>
            <el-button v-else-if="routesByDay[plan.id]" size="small" type="success" @click="viewDayRoute(plan.id)">
              查看路线
            </el-button>
            <el-button v-if="isEditMode && dailyPlans.length > 1" size="small" type="danger" @click="removeDailyPlan(dayIndex)">
              删除当天行程
            </el-button>
          </div>
        </div>
        
        <div class="daily-plan-content">
          <div v-if="plan.locations.length === 0" class="empty-locations">
            <el-empty description="暂无行程安排"></el-empty>
          </div>
          
          <div v-else class="location-list">
            <div v-for="(location, locationIndex) in plan.locations" :key="location.id" class="location-item">
              <!-- 编辑模式 -->
              <template v-if="isEditMode">
                <div class="location-header">
                  <span class="location-index">{{ locationIndex + 1 }}</span>
                  <el-button type="danger" size="small" circle @click="removeLocation(dayIndex, locationIndex)" icon="Delete"></el-button>
                </div>
                
                <el-form label-position="top" class="location-form">
                  <el-form-item label="地点名称">
                    <el-autocomplete
                      v-model="location.name"
                      :fetch-suggestions="(q, cb)=>fetchLocationSuggestions(dayIndex, q, cb)"
                      placeholder="输入地点名称（关键字搜索）"
                      @select="(item)=>onLocationSelect(dayIndex, locationIndex, item)"
                    />
                  </el-form-item>
                  
                  <el-form-item label="地点类型">
                    <el-select v-model="location.type" placeholder="选择地点类型">
                      <el-option label="景点" value="attraction"></el-option>
                      <el-option label="自定义" value="custom"></el-option>
                    </el-select>
                  </el-form-item>
                  
                  <el-form-item label="计划时间">
                    <el-time-picker v-model="location.time" placeholder="选择时间" format="HH:mm" value-format="HH:mm"></el-time-picker>
                  </el-form-item>
                  
                  <el-form-item label="备注">
                    <el-input v-model="location.note" placeholder="添加备注" type="textarea" :rows="2"></el-input>
                  </el-form-item>
                </el-form>
              </template>
              
              <!-- 只读模式 -->
              <template v-else>
                <div class="location-view">
                  <div class="location-view-header">
                    <span class="location-index">{{ locationIndex + 1 }}</span>
                    <span class="location-name">{{ location.name }}</span>
                    <span class="location-time">{{ location.time }}</span>
                  </div>
                  <div class="location-view-content">
                    <el-tag size="small" :type="location.type === 'attraction' ? 'success' : 'info'" class="location-type">
                      {{ location.type === 'attraction' ? '景点' : '自定义' }}
                    </el-tag>
                    <div class="location-note" v-if="location.note">{{ location.note }}</div>
                  </div>
                </div>
              </template>
            </div>
          </div>
          
          <div class="add-location" v-if="isEditMode">
            <el-button type="primary" plain @click="addLocation(dayIndex)">添加地点</el-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.travel-plan-detail {
  padding: 20px;
  max-width: 1000px;
  margin: 0 auto;
}

.plan-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.plan-title {
  margin: 0;
  color: #409EFF;
}

.plan-info {
  margin-bottom: 30px;
}

.plan-description {
  margin-top: 20px;
  background-color: #f5f7fa;
  padding: 15px;
  border-radius: 4px;
}

.plan-description h3 {
  margin-top: 0;
  margin-bottom: 10px;
}

.daily-plans {
  margin-top: 30px;
}

.daily-plans-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.daily-plan-item {
  margin-bottom: 30px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 20px;
}

.daily-plan-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.daily-plan-header h3 {
  margin: 0;
}

.day-note-input {
  width: 60%;
}

.day-note {
  color: #606266;
  font-size: 14px;
  padding: 5px 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.day-route-actions {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-left: auto;
}

.route-badge {
  height: 24px;
  line-height: 24px;
}

.empty-locations {
  padding: 20px;
  text-align: center;
}

.location-list {
  margin-bottom: 15px;
}

.location-item {
  margin-bottom: 15px;
  padding: 15px;
  border: 1px solid #EBEEF5;
  border-radius: 4px;
  background-color: #f5f7fa;
}

.location-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.location-index {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 24px;
  height: 24px;
  background-color: #409EFF;
  color: white;
  border-radius: 50%;
  font-size: 14px;
}

.location-form {
  margin-top: 10px;
}

/* 只读模式样式 */
.location-view {
  padding: 10px;
}

.location-view-header {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.location-name {
  font-weight: 500;
  margin-left: 10px;
  font-size: 16px;
}

.location-time {
  margin-left: auto;
  color: #606266;
}

.location-view-content {
  display: flex;
  flex-direction: column;
  margin-left: 34px;
}

.location-type {
  margin-bottom: 5px;
  width: fit-content;
}

.location-note {
  color: #606266;
  font-size: 14px;
  margin-top: 5px;
  padding: 5px;
  background-color: #ffffff;
  border-radius: 4px;
}

.add-location {
  margin-top: 15px;
  text-align: center;
}

.save-actions {
  margin-top: 20px;
  text-align: center;
}

.edit-actions {
  display: flex;
  gap: 10px;
}
</style>